package nl.runnable.solr.xslt.client;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Representing parameters used in {@link SolrXmlIndexService} operations.
 * <p>
 * The parameters are added to the HTTP query string and are mostly specific to the Solr XSLT Update plugin.
 * 
 * @author Laurens Fridael
 * 
 */
public class Parameters {

	/**
	 * Convenience factory method that creates {@link Parameters} with the commit setting set to <code>true</code>.
	 * 
	 * @return
	 */
	public static Parameters withCommit() {
		final Parameters parameters = new Parameters();
		parameters.setCommit(true);
		return parameters;
	}

	/**
	 * Convenience factory method that creates {@link Parameters} with the commit setting set to <code>false</code>.
	 * 
	 * @return
	 */
	public static Parameters withoutCommit() {
		final Parameters parameters = new Parameters();
		parameters.setCommit(false);
		return parameters;
	}

	private boolean commit = true;

	private String stylesheet;

	private final Map<String, Object> stylesheetParameters = new HashMap<String, Object>();

	/**
	 * Configures whether the <code>commit</code parameter is added to the request. This, in turn, causes the update to
	 * be committed to the Solr index.
	 * 
	 * @return
	 */
	public void setCommit(final boolean commit) {
		this.commit = commit;
	}

	public boolean isCommit() {
		return commit;
	}

	/**
	 * Configures the stylesheet to be applied to the XML content.
	 * 
	 * @return
	 */
	public void setStylesheet(final String stylesheet) {
		this.stylesheet = stylesheet;
	}

	public String getStylesheet() {
		return stylesheet;
	}

	public void addStylesheetParameter(final String name, final String value) {
		Assert.hasText(name, "Stylesheet parameter name cannot be empty.");
		stylesheetParameters.put(name, value);
	}

	/**
	 * Obtains parameters in {@link Map} form.
	 * 
	 * @return
	 */
	public Map<String, String> toMap() {
		final Map<String, String> map = new HashMap<String, String>();
		map.put("commit", isCommit() ? "true" : "false");
		if (StringUtils.hasText(getStylesheet())) {
			map.put("xslt.stylesheet", getStylesheet());
		}
		for (final Entry<String, Object> entry : stylesheetParameters.entrySet()) {
			if (entry.getValue() != null) {
				map.put("xslt.param." + entry.getKey(), entry.getValue().toString());
			}
		}
		return map;
	}

}
